﻿using Aspose.Pdf;
using Aspose.Pdf.Devices;
using NET6.WebAPI.Configs;

namespace NET6.WebAPI.Helpers
{
    public static class AsposePdfHelper
    {
        /*
         * 20.1.0 版本与 .NET 6 不兼容, 生成不了图片, 23.1.0 可以
         */

        /// <summary>
        /// 将 PDF 第一页转换成图片
        /// </summary>
        /// <param name="pdfPath">PDF 文件路径</param>
        /// <returns></returns>
        public static string FirstPageToImage(string pdfPath)
        {
            Document pdf = new Document(pdfPath);
            Page firstPage = pdf.Pages.FirstOrDefault();
            
            using (MemoryStream imageStream = new MemoryStream())
            {
                JpegDevice device = new JpegDevice();
                device.Process(firstPage, imageStream); // 设置分辨率可压缩图片大小

                var imagePath = pdfPath.Replace(FileConfig.Pdf, FileConfig.Jpeg);

                using (FileStream fileStream = new FileStream(imagePath, FileMode.Create, FileAccess.Write))
                {
                    imageStream.Position = 0;
                    imageStream.CopyTo(fileStream);
                }

                return imagePath;
            }
        }
    }
}
